/***
 * 执行云呼call客、连接websocket 的工具js
 * */
var cloudcallUrl = "";
var webSocket;
var heartbeatTarget;//心跳任务
var sessionId;//同时时接收到的sessionId 通过sessionId 进行交互
var lastMsg="";//用于保存上次发送过得数据 === 用于判断是否重复接收相同信息
var lastCallParameter = "";//上一次呼叫的参数 === 用于判断是否重复外呼操作
var callWindowCount = 0;//用于云呼操作的窗体打开的个数
var callStatus="";
var token="";//发送webSocket的参数 ---同时也作为外呼的凭证
var toDoCallTime = null;//执行外呼操作的时间
///=======窗体通讯，就需要根据对应的外呼窗体进行发送外呼行
var cloudCallWinFrameId = "";//当前外呼的窗体frameId === 主要用于返回信息根据对应的窗体返回
var cloudCallWinFrameObj = null;//当前外呼的窗体
var tryConnCount = 5;//自定义重连次数
var isSendSuccess = false;
var pageFromVal = pageFrom;
var callParameter;
var pushCanCallMsg = false;
var connWsHeartbeatTarget = null;//心跳任务
var checkWsHeartbeatTarget = null;//检测心跳任务是否正常
var connectWsVoId = connectWsVo.id;//ws连接的编号id
var closeWinSetTimeOutToCheck = null;
var connStatus = 1; //当前ws连接状态是否异常  1 正常 0 异常/未连接上
var currentConnectExceptionMsg = "";//当前连接异常的错误信息
var currentConnectType = "";//当前连接异常的错误信息
var applyReConnectCallSessionId = "";//请求发起重连[重新获取ws] 操作的sessionId

//websocket 事件对象
var WebSocketEvent = {
    createEvent: function (type, value) {
        var wsEvent = {};
        wsEvent.type = type;
        wsEvent.value = value;
        return wsEvent;
    }
};

//定义一个对象用于处理---是否进行连接操作并且执行外呼操作
var ShowMsgEvent ={
    createEvent: function (sessionId,pageFrom,desc){
        var showMsgEvent ={};
        showMsgEvent.sessionId = sessionId;
        showMsgEvent.pageFrom = pageFrom;
        showMsgEvent.desc = desc;
        return showMsgEvent;
    }
};

//定义页面的提示操作===让页面进行相应的操作
var TipsMsgEvent ={
    createEvent:function (type,sessionId,pageFrom,desc) {
        var tipsMsgEvent = {};
        tipsMsgEvent.type = type;
        tipsMsgEvent.sessionId = sessionId;
        tipsMsgEvent.pageFrom = pageFrom;
        tipsMsgEvent.desc = desc;
        return tipsMsgEvent;
    }
};

//定义页面ws的一个心跳事件 ---》时间是用于判断当前的ws 是否还存活 -- 如果超过10s情况下，视为死亡 ---》发起重新获取ws对象
var HeartbeatEvent = {
    createEvent:function (id,time) {
        var heartBeatEvent={};
        heartBeatEvent.id = id;
        heartBeatEvent.time = time;
        return heartBeatEvent;
    }
};

/**
 * 封装aiCall客的事件 ===》 避免localStorage的存储数据量过多
 * 类型： type
 *   值： value
 * 描述： desc
 * 时间戳 timeStamp ===> 时间戳 由于值的内容相同 localStorage 监听 是值改变了才会触发的
 * */
var AICallEvent = {
  createEvent:function (type,value,desc) {
        var aICallEvent = {};
      aICallEvent.type = type;
      aICallEvent.value = value;
      aICallEvent.desc = desc;
      return aICallEvent;
  }
};

//此webSockect 发送外呼操作，保持一个，不然多个监听，会同时触发多次
//用于监听storage
window.addEventListener("storage", function(event) {
    switch(event.key){
        case "AICallEvent":
            doAIcallEventByType(JSON.parse(event.newValue));
            break;
        case "heartbeatEvent"://检测心跳时间 ==》 保持一个连接时，需实时监测连接的状态是否健康 ===》 检测间隔的心跳  【单独出来是为了检测心跳，不被别的业务处理时间干扰】
            if(event.newValue!=null && event.newValue!=undefined){
                var heartbeatObj = JSON.parse(event.newValue);
                var ms = new Date().getTime() - heartbeatObj.time;   //时间差的毫秒数
                if(ms>6000){//如果接受到已存在超时情况 ===》抢夺政权
                    console.log("检测到目前使用的信鸽"+heartbeatObj.id+"心跳异常，断定为信鸽不健康，通知需获取新的信鸽进行送信操作");
                    connWSToGetToken(connectWsVo);
                    return;
                }
                if(checkWsHeartbeatTarget==null){
                    console.log("检测信鸽"+heartbeatObj.id+"是否健康的心跳机制开启");
                    checkWsHeartbeatTarget = setInterval(checkHearbeatEvent,6000);
                }
            }
            break;
        default:break;
    }
});


/**
 * 根据type 做相应的操作
 * 【压缩同一个处理 主要原因：localstorage 存储空间是有限的，如果仅是页面上的处理，可以尽可能的使用同一个key，避免造成存储量过大情况】
 * */
function doAIcallEventByType(aICallEventObj) {
    try{
        var type = aICallEventObj.type;
        switch (type){
            case "aICallout":
                var callParam = JSON.parse(aICallEventObj.value);
                if(connectWsVo!=null && callParam!=null && (callParam.connWsId == connectWsVo.id  || callParam.sessionId == applyReConnectCallSessionId)){
                    callout(callParam);
                }
                break;
            case "checkIsExists"://检测外呼时的 websocket 连接是否存在
                console.log("检测外呼的ws窗体是否存在");
                if(webSocket != undefined && (webSocket.readyState == WebSocket.OPEN || webSocket.readyState == WebSocket.CONNECTING)) {
                    console.log("外呼窗体存在,告知发起外呼的通话id为："+ aICallEventObj.value);
                    localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("existsWs",aICallEventObj.value,"",new Date().getTime())));
                }
                break;
            case "reConnWs": // 当页面检测 websocket 连接不存在时， 将会发起此操作，让页面进行抢夺连接操作
                console.log("接收到找信鸽的消息了，争取找到优秀的信鸽");
                if(aICallEventObj.value!=null && aICallEventObj.value!=undefined && aICallEventObj.value!=""){
                    var array = aICallEventObj.value.split("_");
                    applyReConnectCallSessionId = aICallEventObj.value.substring(array[0].length+1);
                    console.log(applyReConnectCallSessionId);
                }
                if(connectWsVo!=null){
                    connWSToGetToken(connectWsVo);
                }
                break;
            case "connWsParams"://当有新的websocket连接创建时，判断如果不是当前页面的连接，则关闭当前页面的连接 ===》 保留最新一个websocket连接的 【主要点】
                var currentConnectWsVo = JSON.parse(aICallEventObj.value);
                console.log(currentConnectWsVo.id);
                console.log(connectWsVo.id);
                if(connectWsVo!=null && webSocket!=undefined && currentConnectWsVo.id != connectWsVo.id){
                    webSocket.close();//手动触发关闭时间 ----》确保新连接上的ws是最新的
                    clearInterval(heartbeatTarget);
                    heartbeatTarget = null;
                }
                break;
            case "stopCheckheartBeatEvent"://停止检测心跳事件
                if(aICallEventObj.value==true){
                    if(checkWsHeartbeatTarget==null){
                        console.log("检测信鸽"+heartbeatObj.id+"是否健康的心跳机制开启");
                        checkWsHeartbeatTarget = setInterval(checkHearbeatEvent,6000);
                    }
                }else{
                    clearInterval(checkWsHeartbeatTarget);
                    checkWsHeartbeatTarget = null;
                    //再次接受到心跳时会再次开启
                    var dateTime = new Date().getTime();

                    //如果超过1min钟 则进行设为超时===自己开启检测心跳
                    if(closeWinSetTimeOutToCheck!=null){
                        clearTimeout(closeWinSetTimeOutToCheck);
                    }
                    closeWinSetTimeOutToCheck = setTimeout(function () {
                        if(checkWsHeartbeatTarget==null){
                            console.log("检测信鸽是否健康的心跳机制开启");
                            checkWsHeartbeatTarget = setInterval(checkHearbeatEvent,6000);
                        }
                    },60000);
                }
                break;
            case "changePc"://切换PC操作
                console.log(type+"==========================userId:"+aICallEventObj.value);
                webSocket.send(JSON.stringify({
                    msgType:aICallEventObj.type,
                    userId:aICallEventObj.value,
                    token:token
                }));
                break;
            case "notChangePc"://取消切换PC操作
                token = "";
                clearheartbeatTargetInterval();
                break;
            default:
                break;
        }
    }catch (e){
        console.log("操作异常:"+e.message);
    }
}




/**外呼的方法 */
function callout(jsonObj){
    console.log("信鸽正为您进行送信操作,请耐心等候！");
    //如果发起外呼操作ws是不存在的情况下 === 》 进行连接ws操作
    /*if (webSocket == undefined
        || (webSocket.readyState != WebSocket.OPEN && webSocket.readyState != WebSocket.CONNECTING)) {
        console.log("webSocket连接不存在，尝试连接webSocket");
        var connWsParams = localStorage.getItem("connWsParams");
        if(connWsParams!=undefined && connWsParams!=null){
            connWSToGetToken(localStorage.getItem("connWsParams"));
        }else{
            localStorage.setItem("tipsMsg",TipsMsgEvent.createEvent("connectWsToCall",jsonObj.sessionId,jsonObj.pageFrom,"无法进行获取连接操作操作，请刷新页面后再重试！"));
        }
    }*/
    if(jsonObj.autoRedial != "true" && (lastCallParameter!=null && lastCallParameter !="" && (lastCallParameter.sessionId==jsonObj.sessionId && lastCallParameter.pageFrom==jsonObj.pageFrom))){
        console.log("======非重拨操作，参数一致，识别为重复发送外呼异常操作 直接返回======");
        return ;
    }
    lastCallParameter = jsonObj;
    isSendSuccess = false;//执行的通话的操作是否发送成功标识 初始化false
    toDoCallTime =new Date();//执行外呼的时间
    console.log("=========================call===============================");
    call(jsonObj);
}

/**
 * 传递参数
 * mainCallPhone：主叫号码
 * targetCallPhone：被叫号码
 * dataId：通话记录的id 如为-1则不做保存数据处理
 * showNum：主显号码 (暂不传递)
 * whereFrom:来源app,置业
 * pageFrom:app盘源、app联动CALL,置业盘源、置业联动Call
 * machineFrom:机器码
 * mainCallType:谁呼出.经纪人0/客户1
 * commitTo:提交到哪里：东进(0)/电信(1)
 * createUserId:呼叫经纪id
 * customerName:发起呼叫人的名字
 * mainCallType:谁呼出.经纪人0/客户1
 * 云呼版本  1.0  ，置业默认：maincallPHone:客户号码。targetCallPhone：经纪号码
 * 云呼版本  2.0  ，置业默认：maincallPHone:经纪号码。targetCallPhone：客户号码
 * */
function call(callParameter){
    console.log("callParameter:"+JSON.stringify(callParameter));
    try {
        sessionId = callParameter.sessionId;
        if(webSocket!=undefined){
            console.log(webSocket.readyState);
        }
        if(webSocket != undefined && (webSocket.readyState == WebSocket.OPEN || webSocket.readyState == WebSocket.CONNECTING)) {
            //测试页面pageFrom:5发送的dataId都是0
            console.log("-----进行外呼操作-------");
            isSendSuccess = true;//发送成功
            console.log("callParameter.commitTo========="+callParameter.commitTo+"===========>"+callParameter.aiCall);
            if(callParameter.aiCall == true ){
                console.log("=============进行单呼操作====================");
                var callObj = {
                    msgType: "asrCall",
                    sessionId:callParameter.sessionId,
                    dataId:callParameter.dataId,
                    mainCallPhone: callParameter.mainCallPhone, //'18122027234'
                    whereFrom:callParameter.whereFrom,
                    pageFrom:callParameter.pageFrom,
                    machineFrom:token,
                    callTaskId:callParameter.callTaskId,
                    mainCallType:callParameter.mainCallType,
                    commitTo:callParameter.commitTo,
                    createUserId:callParameter.createUserId,
                    customerName:callParameter.customerName,
                    city:callParameter.cityId,
                    project:callParameter.project,
                    propertyNo:callParameter.propertyNo,
                    objectId:callParameter.objectId,
                    isHide:callParameter.isHide,
                    actionCodeBreak:callParameter.actionCodeBreak,
                    voiceCode:callParameter.voiceCode,
                    packageId:callParameter.packageId,
                    packageName:callParameter.packageName,
                    voiceText:callParameter.voiceText,
                    source:"aiCall"
                };
                if(callParameter.voiceCode == null || callParameter.voiceCode==""){
                    callObj = {
                        msgType: "asrCall",
                        sessionId:callParameter.sessionId,
                        dataId:callParameter.dataId,
                        mainCallPhone: callParameter.mainCallPhone, //'18122027234'
                        whereFrom:callParameter.whereFrom,
                        pageFrom:callParameter.pageFrom,
                        machineFrom:token,
                        callTaskId:callParameter.callTaskId,
                        mainCallType:callParameter.mainCallType,
                        commitTo:callParameter.commitTo,
                        createUserId:callParameter.createUserId,
                        customerName:callParameter.customerName,
                        city:callParameter.cityId,
                        project:callParameter.project,
                        propertyNo:callParameter.propertyNo,
                        objectId:callParameter.objectId,
                        isHide:callParameter.isHide,
                        actionCodeBreak:callParameter.actionCodeBreak,
                        packageId:callParameter.packageId,
                        packageName:callParameter.packageName,
                        voiceText:callParameter.voiceText,
                        source:"aiCall"
                    };
                }
                console.log(JSON.stringify(callObj));

                webSocket.send(JSON.stringify(callObj));
            }else{
                webSocket.send(JSON.stringify({
                    msgType: "asrCall2",//CALL ==》 是普通call客， asrCall2 是 带识别的双呼操作
                    mainCallPhone: callParameter.mainCallPhone, //'18122027234'
                    targetCallPhone: callParameter.targetCallPhone,
                    sessionId:callParameter.sessionId,
                    dataId:callParameter.dataId,
                    whereFrom:callParameter.whereFrom,
                    pageFrom:callParameter.pageFrom,
                    machineFrom:token,
                    callTaskId:callParameter.callTaskId,
                    mainCallType:callParameter.mainCallType,
                    commitTo:callParameter.commitTo,
                    createUserId:callParameter.createUserId,
                    customerName:callParameter.customerName,
                    city:callParameter.cityId,
                    project:callParameter.project,
                    propertyNo:callParameter.propertyNo,
                    objectId:callParameter.objectId,
                    isHide:callParameter.isHide,
                    packageId:callParameter.packageId,
                    packageName:callParameter.packageName,
                    source:"aiCall"
                }));
            }
            localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("callSuccess",callParameter.sessionId,callParameter.pageFrom,"外呼成功")));
        } else {
            console.log("======ConnectWSToCall=====");
            connWSToGetToken(localStorage.getItem("urlParameter"), function() {
                call(callParameter);
            });
        }
    }catch (e) {
        console.log("call error");
        console.log(e);
        console.log(e.message);
        localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("callError",callParameter.sessionId,callParameter.pageFrom,"外呼失败")));
    }
}



function connWSToGetToken(connWsParams) {
    var existsHeartbeatStr = localStorage.getItem("heartbeatEvent");
    try {
        if(existsHeartbeatStr!=null){
            var existsHeartbeatObj = JSON.parse(existsHeartbeatStr);
            var ms = new Date().getTime() - existsHeartbeatObj.time;   //时间差的毫秒数
            if(ms<=5000 && existsHeartbeatObj.id!=connWsParams.id){
                console.log("=========已经有信鸽"+existsHeartbeatObj.id+"了,不用再找啦！========");
                return;
            }
        }
        if(webSocket!=undefined){
            console.log(webSocket.readyState);
        }
        if (webSocket == undefined
            || (webSocket.readyState != WebSocket.OPEN && webSocket.readyState != WebSocket.CONNECTING)) {
            var timestamp = new Date().getTime();//获取当前的时间戳
            /* connectWindowFrameId = connWsParams.windowFrameId; //连接ws时，根据传递过来的子窗体参数 来获取通信的子窗体
            setConnectWindow(connectWindowFrameId);*/
            var targetPhone = localStorage.getItem("targetCallPhone");
            if(targetPhone != "" && targetPhone!=null &&  targetPhone.toUpperCase()!="NULL"){
                connWsParams.machineId  = targetPhone;
                connWsParams.userId  = targetPhone;//TODO 因为没有指定用户，所以采用此方式，避免都有切换PC的提示情况
            }
            console.log(connWsParams.url);
            var cloudCallUrl = connWsParams.url
                + "?token="
                + connWsParams.machineId + "_" + timestamp + "&userId=" + connWsParams.userId
                + "&pageFrom=" + connWsParams.pageFrom+"&source=aiCall";
            token = connWsParams.machineId + "_" + timestamp;
            console.log(cloudCallUrl);
            webSocket = new WebSocket(cloudCallUrl);
            console.log("正在寻找信鸽"+connectWsVoId+"...");
            webSocket.onopen = function (event) {
                callback(event);
                connStatus = 1;
                currentConnectExceptionMsg = "";
                currentConnectType = "";
                console.log(" currentConnectType========="+currentConnectType);
            };
            webSocket.onmessage = function (event) {
                console.log(event);
                callback(event);
            };
            webSocket.onclose = function (event) {
                //清除心跳任务
                clearInterval(heartbeatTarget);
                heartbeatTarget = null;
                callback(event);
                //清除页面发送心跳
                clearheartbeatTargetInterval();
            };
            webSocket.onerror = function (event) {
                callback(event);
                //清除页面发送心跳
                clearheartbeatTargetInterval();
            };
            if (heartbeatTarget == null) {
                heartbeatTarget = setInterval("heartbeat()", 10000);
            }
        }else{
            if (token == "") {
                var desc = "连接失败，请稍后重试。";
                connStatus = 0;
                currentConnectType = "error";
                currentConnectExceptionMsg = "连接失败，请稍后重试。";
                console.log(" currentConnectType========="+currentConnectType);
            }else{
                //将当前页面的异常信息返回给页面
                if(connStatus == 0){
                    localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent(currentConnectType,applyReConnectCallSessionId,"",currentConnectExceptionMsg)));
                }else{//当前ws连接正常情况下 ==》
                    console.log("再次进行重连操作！！！！！！！");
                    webSocket = undefined;
                    connWSToGetToken(connWsParams);
                }
            }

        }
    }catch (e){
        console.log("创建连接异常"+e.message);
        if(callParameter!=null){
            localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("callError",callParameter.sessionId,callParameter.pageFrom,"创建连接异常")));
        }else{
            localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("callError","","","创建连接异常")));
            connStatus = 0;
            currentConnectType = "error";
            currentConnectExceptionMsg = "创建连接异常";
            console.log(" currentConnectType========="+currentConnectType);
        }
    }
}

//发送心跳包
function heartbeat() {
    try {
        if(webSocket != undefined && (webSocket.readyState == WebSocket.OPEN || webSocket.readyState == WebSocket.CONNECTING)) {
            webSocket.send(JSON.stringify({
                msgType:"BEAT",
                token:token
            }));
        }else {
            console.log("发送心跳操作==>判断websocket尚未连接成功")
        }
    } catch (e) {
        console.log("send heartbeat error");
        console.log(e.message);
    }
}

//发送ws存在的心跳 localStorage
function heartbeatTolocalStorage() {
    try {
        if(webSocket != undefined && (webSocket.readyState != WebSocket.CLOSED && webSocket.readyState != WebSocket.ERROR))
        {
            localStorage.setItem("heartbeatEvent",JSON.stringify(HeartbeatEvent.createEvent(connectWsVo.id,new Date().getTime())));
        }
    }catch (e){
        console.log("发送心跳任务异常"+e.message);
    }
}

//定时 查看 heartbeat 情况
function checkHearbeatEvent() {
    try {
        //如果心跳再次开启后 === 判断 延时检测任务存在时，进行clear清除掉
        if(closeWinSetTimeOutToCheck!=null){
            clearTimeout(closeWinSetTimeOutToCheck);
        }
        var heartbeatEvent = localStorage.getItem("heartbeatEvent");
        if(heartbeatEvent!=null){
            var ms = new Date().getTime() - JSON.parse(heartbeatEvent).time;
            if(ms>6000){
                connWSToGetToken(connectWsVo);
                return;
            }
        }
    }catch (e){
        console.log("检测信鸽心跳任务异常："+e.message);
    }
}

//回调函数
function callback(event){
    console.log(event);
    try{
        switch (event.type) {
            case "open":
                console.log("onOpen " + new Date());
                localStorage.setItem("WebSocketEvent", JSON.stringify(WebSocketEvent.createEvent("open", "")));
                if(cloudCallWinFrameObj!=null && cloudCallWinFrameObj!=undefined){
                    console.log(cloudCallWinFrameObj);
                }
                break;
            case "message":
                console.log("onMessage " + event.data +new Date());
                var value = event.data;
                var dataObj = JSON.parse(event.data);
                console.log("=========连接websocket并获取该websocket对应的凭证=======");
                if(dataObj["msgType"] == "WEBSOCKET_CONNECT_MSG"){
                    var desc = dataObj["desc"];
                    var code = dataObj["code"];
                    if(code >0 && "websocket连接可用" == desc){
                        console.log("信鸽"+connectWsVoId+"目前可用！");
                        localStorage.setItem("AICallEvent",JSON.stringify(AICallEvent.createEvent("connWsParams",JSON.stringify(connectWsVo),"连接Ws的参数")));

                        if (connWsHeartbeatTarget == null) {
                            console.log("检测信鸽"+connectWsVoId+"的心跳任务开启");
                            connWsHeartbeatTarget = setInterval(heartbeatTolocalStorage, 5000);
                        }
                        if(checkWsHeartbeatTarget==null){
                            console.log("检测信鸽"+connectWsVoId+"的心跳是否异常或者逾时未响应的任务开启");
                            checkWsHeartbeatTarget = setInterval(checkHearbeatEvent,6000);
                        }
                    }else{
                        console.log("请不要使用多台电脑外呼。如果要切换到此台电脑外呼，上一台电脑将停止外呼。");
                        localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("changePC",applyReConnectCallSessionId,"",desc)));
                        connStatus = 0;
                        currentConnectType = "changePC";
                        currentConnectExceptionMsg = desc;
                        console.log(" currentConnectType========="+currentConnectType);
                        return;
                    }
                }
                if(dataObj["msgType"] == "WEBSOCKET_NOT_RECONNECT_MSG"){//断开后---不需要重新连接websocket.
                    console.log("WEBSOCKET_NOT_RECONNECT_MSG,目前金主要求换信鸽啊，任性到不行，所以只能舍弃这个信鸽了！！！");
                    webSocket.close();
                    tryConnCount = -1;//尝试重连次数为-1
                    token = "";
                    return ;
                }
                if(dataObj["msgType"] == "WEBSOCKET_TOO_MANY_CONNECT_MSG"){
                    console.log("目前太多信鸽了，不能再买了信鸽"+connectWsVoId+"，要没钱了");
                    // zk.Widget.$('$txResult').setValue(desc);
                    layer.msg(dataObj["desc"]);
                    localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("tooManyConnectMsg",applyReConnectCallSessionId,"",dataObj["desc"])));
                    isCallEnd = true;//更新标识---通话结束
                    isCallException = true;
                    connStatus = 0;
                    currentConnectExceptionMsg = dataObj["desc"];
                    currentConnectType = "tooManyConnectMsg";
                    applyReConnectCallSessionId = "";//再次发起重连时清空
                    console.log("currentConnectType========="+currentConnectType);
                    return ;
                }
                if(dataObj["msgType"] == "WEBSOCKET_CHANGE_PC_MSG"){//接收到信息--返回切换成功再通知窗体可以进行外呼操作
                    // receiveChangePcSuccess
                    connStatus = 1;
                    currentConnectExceptionMsg = "";
                    currentConnectType = "";
                    //{ports: Array[0], data: "{"msgType":"WEBSOCKET_CHANGE_PC_MSG","code":"1","time":"20190114112255479","desc":"切换成功"}", source: null, lastEventId: "", origin: "ws://113.108.202.235:7771"…}
                    console.log("WEBSOCKET_CHANGE_PC_MSG currentConnectType========="+currentConnectType);
                    if("1" == dataObj["code"]){
                        localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("websocketChangePCMsg",applyReConnectCallSessionId,"",dataObj["desc"])));

                        if (connWsHeartbeatTarget == null) {
                            console.log("检测信鸽"+connectWsVoId+"的心跳任务开启");
                            connWsHeartbeatTarget = setInterval(heartbeatTolocalStorage, 5000);
                        }
                        //开启检测机制
                        if(checkWsHeartbeatTarget==null){
                            console.log("检测信鸽"+connectWsVoId+"的心跳是否异常或者逾时未响应的任务开启");
                            checkWsHeartbeatTarget = setInterval(checkHearbeatEvent,6000);
                        }
                    }
                }
                console.log("用于告知其他窗体，信鸽返回的信息情况");
                localStorage.setItem("WebSocketEvent", JSON.stringify(WebSocketEvent.createEvent("message", event.data)));//传递到别的Tab进行处理
                break;
            case "error":
                console.log("onError " + new Date());
                console.log("目前信鸽"+connectWsVoId+"情况异常");
                //清除页面发送心跳
                clearheartbeatTargetInterval();
                if(callParameter!=undefined){
                    localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("error",sessionId ,callParameter.pageFrom, "获取连接异常")));
                }else{
                    localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("error",applyReConnectCallSessionId ,"", "获取连接异常")));
                    connStatus = 0;
                    currentConnectExceptionMsg = "获取连接异常";
                    applyReConnectCallSessionId = "";
                    currentConnectType = "error";
                    console.log(" currentConnectType========="+currentConnectType);
                }
                break;
            case "close":
                console.log("onClose " + new Date());
                console.log("目前信鸽"+connectWsVoId+"已经挂了");
                //清除页面发送心跳
                clearheartbeatTargetInterval();
                if(callParameter!=undefined){
                    localStorage.setItem("TipsMsgEvent",JSON.stringify(TipsMsgEvent.createEvent("close",sessionId ,callParameter.pageFrom, "获取连接已关闭")));
                }else {
                    localStorage.setItem("TipsMsgEvent", JSON.stringify(TipsMsgEvent.createEvent("close",applyReConnectCallSessionId, "", "获取连接已关闭")));
                    connStatus = 0;
                    currentConnectExceptionMsg = "获取连接已关闭";
                    currentConnectType = "close";
                    applyReConnectCallSessionId = "";
                    console.log(" currentConnectType========="+currentConnectType);
                }
                break;
            default:
                break;
        }
    }catch (e){
        console.log("接收处理信鸽返回信息的操作异常"+e.message);
    }
}

/**
 * 清除心跳检测事件
 * */
function clearheartbeatTargetInterval(){
    if(connWsHeartbeatTarget!=null){
        clearInterval(connWsHeartbeatTarget);
        connWsHeartbeatTarget = null;
    }
    if(checkWsHeartbeatTarget!=null){
        clearInterval(checkWsHeartbeatTarget);
        checkWsHeartbeatTarget = null;
    }
    if(connectWsVo!=null){
        var existsHeartbeatStr = localStorage.getItem("heartbeatEvent");
        try {
            if (existsHeartbeatStr != null) {
                var existsHeartbeatObj = JSON.parse(existsHeartbeatStr);
                //移除心跳 在localstorage 存储的值
                if (existsHeartbeatObj.id == connectWsVo.id) {
                    localStorage.removeItem("heartbeatEvent");
                }
            }
        }catch (e){
            console.log("移除检测信鸽心跳事件异常！"+e.message);
        }
    }
}

//在即将离开当前页面（刷新或关闭）时触发
window.onbeforeunload = function() {
    var existsHeartbeatStr = localStorage.getItem("heartbeatEvent");
    try{
        if (existsHeartbeatStr != null) {
            var existsHeartbeatObj = JSON.parse(existsHeartbeatStr);
            var ms = new Date().getTime() - existsHeartbeatObj.time;   //时间差的毫秒数
            if (ms <= 5000 && existsHeartbeatObj.id == connectWsVo.id) {
                localStorage.setItem("AICallEvent",JSON.stringify(AICallEvent.createEvent("stopCheckheartBeatEvent",false,"暂时检测心跳事件"+new Date().getTime())));
                console.log("目前送信的信鸽很健康，你确定要舍弃？");
                return "重新加载或关闭窗体,会导致正在外呼的通话状态无法返回,您确定要重新加载窗体?";
            }
        }
    }catch (e){
        console.log("舍弃信鸽操作异常"+e.message);
    }
};

/**
 * 当用户弹出页面关闭框，点击“留下此页”后触发的
 * */
window.onunloadcancel = function(){
    console.log("取消重新加载或关闭窗体操作");
};


/**
 * 当页面关闭后,会触发unload事件
 * */
window.onunload = function () {
    console.log("关闭页面");
    localStorage.setItem("AICallEvent",JSON.stringify(AICallEvent.createEvent("stopCheckheartBeatEvent",true,"恢复检测心跳事件"+new Date().getTime())));
    return;
};

